#pragma once

#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>

#include"../comm/util.hpp"
#include"../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;
    class Compiler
    {
        public:
        Compiler(){}
        ~Compiler(){}
        static bool Complie(const std::string &file_name)
        {
            pid_t res = fork();
            if(res == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompilerError(file_name).c_str(), O_CREAT | O_WRONLY, 644);
                if(_stderr < 0)
                {
                    LOG(WARRING) << "没有成功形成stderr文件" << "\n";
                    exit(1);
                }
                //重定向
                dup2(_stderr, 2);
                //编译
                execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(), PathUtil::Src(file_name).c_str(), "-DCompiler_run","-std=c++11", nullptr);
                LOG(ERROR) << "启动g++编译器失败" << "\n";
                exit(2);
            }
            else if(res < 0)
            {
                LOG(ERROR) << "创建子进程失败！" << std::endl;
                return false;
            }
            else
            {
                //父进程
                waitpid(res, nullptr, 0);
                if(FileUtil::IsFileExits(PathUtil::Exe(file_name)))
                {
                    LOG(INFO) << PathUtil::Src(file_name) << "编译成功" << "\n";
                    return true;
                }
            }
            LOG(ERROR) << "编译失败" << "\n";
            return false;
        }
    };
}